package com.example.banksystem.service;

import com.example.banksystem.dto.TransferRequest;
import com.example.banksystem.entity.Transaction;
import com.example.banksystem.TransactionType;
import com.example.banksystem.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;

@Service
public class TransferService {
    private final AccountService accountService;
    private final TransactionServer transactionServer;

    // 构造函数注入依赖
    public TransferService(AccountService accountService, TransactionServer transactionServer) {
        this.accountService = accountService;
        this.transactionServer = transactionServer;
    }

    // 转账核心方法（事务保证原子性）
    @Transactional(rollbackFor = Exception.class)
    public Transaction transfer(TransferRequest request) {
        try {
            // 1. 查询付款账户和收款账户
            var sourceAccount = accountService.getAccountByCardNumber(request.getSourceCard());
            var targetAccount = accountService.getAccountByCardNumber(request.getTargetCard());

            // 2. 验证交易密码
            accountService.verifyTransactionPassword(sourceAccount, request.getTransactionPwd());

            // 3. 扣减付款账户余额
            accountService.deductBalance(sourceAccount, request.getAmount());

            // 4. 增加收款账户余额
            accountService.increaseBalance(targetAccount, request.getAmount());

            // 5. 记录转账交易
            Transaction transaction = new Transaction();
            transaction.setType(TransactionType.TRANSFER);
            transaction.setTime(LocalDateTime.now());
            transaction.setSourceAccount(sourceAccount.getAccountId());
            transaction.setTargetAccount(targetAccount.getAccountId());
            transaction.setAmount(request.getAmount());
            transaction.setRemark(request.getRemark());

            return transactionServer.saveTransaction(transaction);
        } catch (Exception e) {
            throw new BusinessException("转账失败：" + e.getMessage());
        }
    }
}